import React, { useEffect, useState } from "react";
import { Button, Card, Divider, Drawer, Form, Input, Select, Tag, Tooltip } from "antd";
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";
import TaskConfigurationClass from "./index,module.css"
import {
    ASSIGNEETYPE, DOCUMENTATION,
    FLowCustomNameList
} from "@/components/properties-panel-extension/config/CustomName.ts"
import { ScheduleOutlined, SearchOutlined, UserOutlined } from "@ant-design/icons";
import UserTableView from "@/components/properties-panel-extension/components/TaskConfiguration/components/userTable";
import CheckExpressionTableView
    from "@/components/properties-panel-extension/components/TaskConfiguration/components/checkExpressionTable";
import RoleTableView from "@/components/properties-panel-extension/components/TaskConfiguration/components/roleTable";
import { globalMessage } from "@/utils/message";
import { listUser } from "@/api/system/user";
import { listRole } from "@/api/system/role";
import { listExpression } from "@/api/flowable/definition/expression";

interface MyComponentProps {
    bpmnInstance: any,
}

interface DefaultOptionType {
    value: string;
    label: string;
    key?: string;
}

interface ExecutionListenerElement {
    $type: string;
    event: string;
    class?: string;
    expression?: string;
    delegateExpression?: string;
}

// 任务配置组件
const TaskConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const { bpmnInstance } = props
    const { moddle, modeling, bpmnElement = {}, elementRegistry, bpmnFactory } = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();
    const [selectType, setSelectType] = useState<object>({})
    const [procesOpen, setProcessOpen] = useState<boolean>(false);//选择用户弹窗
    const [selectedCheckType, setSelectedCheckType] = useState<"checkbox" | "radio">("radio")//表格单选/复选
    const [selectList, setSelectList] = useState([])//表格选中的数据
    const [checkClickType, setCheckClickType] = useState<string>("checkUser")
    const [processCarbonCopyOpen, setProcessCarbonCopyOpen] = useState<boolean>(false);
    const [selectCarbonCopyList, setSelectCarbonCopyList] = useState([])//抄送表格选中的数据
    useEffect(() => {

        // 获取基础属性
        const dataType = bpmnElement.businessObject.get("flowable:dataType");
        const dataValue = bpmnElement.businessObject.get(`flowable:${dataType}`);

        // 获取 carbonCopy 扩展属性
        const extensionElements = bpmnElement.businessObject.get("extensionElements");
        let carbonCopy = null;

        if (extensionElements) {
            // 查找 flowable:carbonCopy 扩展元素
            const carbonCopyElement = extensionElements.get("values")
                .find((ext: any) => ext.$type === "flowable:CarbonCopy");
            if (carbonCopyElement) {
                carbonCopy = carbonCopyElement.values;
                getCarbonCopyUserList(carbonCopy.split(",").map(Number))
            }
        }

        // 设置状态
        setBaseInfo({
            ...bpmnElement.businessObject,
            dataType,
            dataValue,
            carbonCopy: carbonCopy ? carbonCopy.split(",").map(Number) : [] // 转换为数字数组
        });
        setSelectList([])
        setSelectCarbonCopyList([])
        handleLoading(dataType, dataValue)

    }, [bpmnElement.businessObject]);
    const handleLoading = (type: string, Ids: string) => {
        if (isTemplateParam(Ids)) {
            getExpressionList(Ids)
        } else {
            switch (type) {
                case "assignee":
                    getUserList(Ids.split(',').map(Number))
                    break;
                case "candidateGroups":
                    getRoleList(Ids.split(',').map(Number))
                    break;
                case "candidateUsers":
                    getUserList(Ids.split(',').map(Number))
                    break;
            }
        }
    }
    const isTemplateParam = (str: string) => {
        return /^\$\{\w+\}$/.test(str);
    }
    /** 查询用户列表 */
    const getUserList = (userIds: any[]) => {
        listUser({ userIds }).then((res: any) => {
            setSelectList(res.rows.map((item: any) => ({
                ...item,
                deptName: item.dept?.deptName,
                key: item.userId // 使用 userId 作为唯一的 key
            })))
        });
    }
    /** 查询用户列表 */
    const getCarbonCopyUserList = (userIds: any[]) => {
        listUser({ userIds }).then((res: any) => {
            setSelectCarbonCopyList(res.rows.map((item: any) => ({
                ...item,
                deptName: item.dept?.deptName,
                key: item.userId // 使用 userId 作为唯一的 key
            })))

        });
    }
    /** 查询表达式列表 */
    const getExpressionList = (expression: string) => {
        listExpression({ expression }).then((res: any) => {
            setSelectList(res.rows.map((item: any) => ({
                ...item,
                key: item.id // 使用 userId 作为唯一的 key
            })))
        });
    }
    /** 查询群组列表 */
    function getRoleList(roleIds: any[]) {
        listRole({ roleIds }).then((res: any) => {
            setSelectList(res.rows.map((item: any) => ({
                ...item,
                key: item.roleId // 使用 userId 作为唯一的 key
            })))
        });
    }

    // 改变配置信息
    const baseInfoChange = (value: any, obj?: Object) => {
        setSelectType({ ...obj })
        switch (value) {
            case "assignee":
                setSelectedCheckType("radio")
                break;
            case "candidateGroups":
                setSelectedCheckType("checkbox")
                break;
            case "candidateUsers":
                setSelectedCheckType("checkbox")
                break;

        }
        setBaseInfo({ ...baseInfo, dataType: value, dataValue: null });
        setSelectList([])
        // 清除不相关的属性
        const propertiesToRemove = {};
        dataTypeList.forEach((item) => {
            if (item.value !== value) {
                propertiesToRemove[`flowable:${item.value}`] = undefined;
            }
        })
        // 更新属性
        modeling.updateProperties(bpmnElement, propertiesToRemove);
    };
    const baseInfoValueChange = (value: any) => {
        setBaseInfo({ ...baseInfo, dataValue: value });
        const properties = {};
        properties[`flowable:${baseInfo.dataType}`] = value || undefined;
        modeling.updateProperties(bpmnElement, { ...properties });
        modeling.updateProperties(bpmnElement, { "flowable:dataType": baseInfo.dataType || undefined });
    };
    // 改变抄送
    const baseInfoCarbonCopyValueChange = (value: any) => {
        // setBaseInfo({ ...baseInfo, dataValue: value });
        // 获取或创建扩展元素

        let extensionElements = bpmnElement.businessObject.extensionElements;
        if (!extensionElements) {
            extensionElements = moddle.create('bpmn:ExtensionElements', { values: [] });
        }
        // 过滤掉旧的抄送
        const otherElements = (extensionElements.values || []).filter(
            (item: ExecutionListenerElement) => item.$type !== 'flowable:CarbonCopy',
        );
        let flowableCcUsers = null;
        if (value) {
            flowableCcUsers = moddle.create('flowable:CarbonCopy', { values: value });
        }

        // 更新扩展元素
        extensionElements.values = [...otherElements, ...(flowableCcUsers ? [flowableCcUsers] : [])];

        // 更新属性
        modeling.updateProperties(bpmnElement, {
            extensionElements: extensionElements.values.length > 0
                ? extensionElements
                : undefined,
        });



    };
    const dataTypeList: DefaultOptionType[] = [
        {
            key: "user",
            value: "assignee",
            label: '用户',
        }, {
            key: "group",
            value: "candidateUsers",
            label: '用户组(候选)',
        }, {
            key: "role",
            value: "candidateGroups",
            label: '角色(候选)',
        },
        // {
        //     value: "position",
        //     label: '岗位',
        //     key: "candidateGroups",
        // },
        // {
        //     key: "expression",
        //     value: "expression",
        //     label: '表达式',
        // },
    ]
    const dataTypeMap = dataTypeList.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
    }, {} as Record<string, string>);
    // 标签删除
    const preventDefault = (e) => {
        let List = []
        if (checkClickType == "checkUser") {
            switch (baseInfo.dataType) {
                case "candidateGroups":
                    List = selectList.filter(item => item.roleId != e.roleId)
                    break;
                case "candidateUsers":
                    List = selectList.filter(item => item.userId != e.userId)
                    break;
                default:
                    break;
            }
        }
        if (checkClickType == "CheckExpression") {
            List = selectList.filter(item => item.id != e.id)
        }
        checkList(List)
        setSelectList(List)
    }
    // 抄送删除
    const preventCarbonCopyDefault = (e: any) => {
        let List = []
        List = selectCarbonCopyList.filter(item => item.userId != e.userId)
        setSelectCarbonCopyList(List)
        checkCarbonCopyList(List)
    }
    //用户，用户组，角色，弹窗选中
    const SelectRadioOption = (e) => {
        console.log("EEEEE", e)
        setSelectList(e)
        checkList(e)
    }
    // 弹窗选中
    const SelectCarbonCopyOption = (e) => {
        console.log("EEEEE", e)
        setSelectCarbonCopyList(e)
        checkCarbonCopyList(e)
    }
    //选中和取消抄送更改参数
    const checkCarbonCopyList = (e) => {
        const ids = e
            .map((item: any) => item.userId)
            .filter((id: string) => id != null) // 过滤掉 null/undefined
            .join(',');
        baseInfoCarbonCopyValueChange(ids)
    }
    //选中和取消用户和角色后更改参数
    const checkList = (e) => {
        let ids = ''
        if (checkClickType == "checkUser") {
            switch (baseInfo.dataType) {
                case "assignee":
                    ids = e
                        .map((item: any) => item.userId)
                        .filter((id: string) => id != null) // 过滤掉 null/undefined
                        .join(',');
                    break;
                case "candidateUsers":
                    ids = e
                        .map((item: any) => item.userId)
                        .filter((id: string) => id != null) // 过滤掉 null/undefined
                        .join(',');
                    break;
                case "candidateGroups":
                    ids = e
                        .map((item: any) => item.roleId)
                        .filter((id: string) => id != null) // 过滤掉 null/undefined
                        .join(',');
                    break;
            }
        }

        if (checkClickType == "CheckExpression") {
            ids = e
                .map((item: any) => item.expression)
                .filter((id: string) => id != null) // 过滤掉 null/undefined
                .join(',');
        }
        baseInfoValueChange(ids)
    }
    // 按钮点击类型
    const handleCheck = (e) => {
        switch (e) {
            case "checkUser":
                setSelectedCheckType(baseInfo.dataType == "assignee" ? "radio" : "checkbox")
                setCheckClickType(e)
                break;
            case "CheckExpression":
                setSelectedCheckType("radio")
                setCheckClickType(e)
                break;

        }
        setProcessOpen(true);
    }
    // 按钮点击类型
    const handleCarbonCopyCheck = () => {
        setSelectedCheckType("checkbox")
        setProcessCarbonCopyOpen(true);
    }



    return (
        <>
            <Card
                className={baseInformationClass.CardClass}
                title={`任务配置`}
                extra={null}>
                <Form>
                    <Form.Item
                        label="代办人类型"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <Select
                            value={[baseInfo?.dataType]}
                            defaultValue={[baseInfo?.dataType]}
                            style={{ width: '80%' }}
                            options={dataTypeList}
                            onChange={(e, option) => baseInfoChange(e, option)}
                        />
                    </Form.Item>
                    <Form.Item
                        label={`${dataTypeMap[baseInfo?.dataType] || ''}ID`}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <div className={'p-0.5 border rounded-md min-h-8'}>
                            {selectList.map((item) => (
                                <Tag key={item.userId || item.roleId || item.id} closeIcon closable onClose={(e) => {
                                    preventDefault(item)
                                }}>
                                    {item.userName || item.roleName || item.expression}
                                </Tag>
                            ))}

                        </div>
                        <Tooltip placement="bottom" title={dataTypeMap[baseInfo?.dataType]}>
                            <Button icon={<UserOutlined />} onClick={() => handleCheck("checkUser")} />
                        </Tooltip>
                        <Tooltip placement="bottom" title={"表达式"}>
                            <Button icon={<ScheduleOutlined />} onClick={() => handleCheck("CheckExpression")} />
                        </Tooltip>
                        {/*<Input*/}
                        {/*    value={baseInfo?.dataValue}*/}
                        {/*    onChange={(e) => baseInfoValueChange(e.target.value)}*/}
                        {/*/>*/}
                    </Form.Item>
                    <Divider >抄送</Divider>

                    <Form.Item
                        label="抄送人员"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <div className={'p-0.5 border rounded-md min-h-8'}>
                            {selectCarbonCopyList.map((item) => (
                                <Tag key={item.userId} closeIcon closable onClose={(e) => {
                                    preventCarbonCopyDefault(item)
                                }}>
                                    {item.userName}
                                </Tag>
                            ))}

                        </div>
                        <Tooltip placement="bottom" title={"抄送"}>
                            <Button onClick={() => handleCarbonCopyCheck()} >抄送</Button>
                        </Tooltip>
                    </Form.Item>
                </Form>
            </Card>
            <Drawer
                title="信息"
                placement="left"
                closable={false}
                onClose={() => {
                    setProcessOpen(false)
                }}
                open={procesOpen}
                width={"50%"}
                key={"right"}
                footer={
                    <div className={"flex justify-end"}>
                        <Button
                            type={"primary"}
                            onClick={() => setProcessOpen(false)}>确认</Button>
                    </div>

                }>
                {/* 用户或者用户组*/}
                {procesOpen && checkClickType == "checkUser" && baseInfo.dataType !== "candidateGroups" && (
                    <UserTableView
                        type={selectedCheckType}
                        SelectOption={(e) => SelectRadioOption(e)}></UserTableView>)}
                {/* 选择角色 */}
                {procesOpen && checkClickType == "checkUser" && baseInfo.dataType == "candidateGroups" && (
                    <RoleTableView
                        type={selectedCheckType}
                        SelectOption={(e) => SelectRadioOption(e)}></RoleTableView>)}
                {/* 选择表达式 */}
                {procesOpen && checkClickType == "CheckExpression" && (<CheckExpressionTableView
                    type={selectedCheckType}
                    SelectOption={(e) => SelectRadioOption(e)}></CheckExpressionTableView>)}

            </Drawer>
            <Drawer
                title="抄送"
                placement="left"
                closable={false}
                onClose={() => {
                    setProcessCarbonCopyOpen(false)
                }}
                open={processCarbonCopyOpen}
                width={"50%"}
                key={"CarbonCopy"}
                footer={
                    <div className={"flex justify-end"}>
                        <Button
                            type={"primary"}
                            onClick={() => setProcessCarbonCopyOpen(false)}>确认</Button>
                    </div>
                }>
                {/* 选择抄送 */}
                {processCarbonCopyOpen && (<UserTableView
                    type={selectedCheckType}
                    SelectOption={(e) => SelectCarbonCopyOption(e)}></UserTableView>)}
            </Drawer>
        </>

    );
}
    ;

export default TaskConfigurationView;
